package drds.server.route.shard_algorithm;

import drds.server.route.util.DataPartitionTool;
import drds.server.util.SplitUtil;

public final class ByLong extends AbstractShardAlgorithm implements ShardAlgorithm {
	protected int[] counts;
	protected int[] lengths;
	protected DataPartitionTool dataPartitionTool;

	private static int[] toIntArray(String string) {
		String[] strings = SplitUtil.split(string, ',', true);
		int[] ints = new int[strings.length];
		for (int i = 0; i < strings.length; ++i) {
			ints[i] = Integer.parseInt(strings[i]);
		}
		return ints;
	}

	public void setPartitionCount(String counts) {
		this.counts = toIntArray(counts);
	}

	public void setPartitionLength(String lengths) {
		this.lengths = toIntArray(lengths);
	}

	@Override
	public void init() {
		dataPartitionTool = new DataPartitionTool(counts, lengths);

	}

	@Override
	public Integer calculate(String columnValue) {
		try {
			long key = Long.parseLong(columnValue);
			return dataPartitionTool.hash(key);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException(new StringBuilder().append("columnValue:").append(columnValue).append(" Please eliminate any quote and non number within it.").toString(), e);
		}
	}

	@Override
	public Integer[] calculateRange(String beginColumnValue, String endColumnValue) {
		return AbstractShardAlgorithm.calculateRange(this, beginColumnValue, endColumnValue);
	}

}